package com.org.service.impl;

import com.org.exception.BaseException;
import com.org.properties.EmailProperties;
import com.org.service.EmailService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

import java.util.Random;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
@RequiredArgsConstructor
public class EmailServiceImpl implements EmailService {

    private final JavaMailSender mailSender;

    private final StringRedisTemplate redisTemplate;

    private final EmailProperties emailProperties;

    /**
     * 发送邮件
     * @param email
     */
    @Override
    public boolean sendEmail(String email) {
        if(email != null){
            //1.1、判断邮箱格式是否正确
            if(!(email.matches("^[a-zA-Z0-9_+-]+@[a-zA-Z0-9-]+(\\.[a-zA-Z0-9-]+)*\\.[a-zA-Z]{2,}$"))){
                throw new BaseException("邮箱格式错误");
            }
        }else{
            throw new BaseException("邮箱不能为空");
        }
        // 1. 生成验证码
        String code = generateCode();

        // 2. 发送邮件
        try {
            SimpleMailMessage message = new SimpleMailMessage();
            message.setFrom(emailProperties.getUsername());
            message.setTo(email);
            message.setSubject("验证码通知");
            message.setText("您的验证码是：" + code + "，5分钟内有效。");

            mailSender.send(message);

            // 3. 存入Redis，5分钟过期
            redisTemplate.opsForValue().set("email:code:" + email,code,5, TimeUnit.MINUTES);

            return true;
        } catch (Exception e) {
            log.error("邮件发送失败=>", e);
            throw new BaseException("邮件发送失败");
        }
    }

    /**
     * 验证码验证
     * @param email 邮箱
     * @param code 验证码
     * @return
     */
    @Override
    public boolean verifyCode(String email, String code) {
        // 从Redis获取验证码
        String storedCode;
        if (email.contains("@")) {   //判断是邮箱还是手机号
            storedCode = redisTemplate.opsForValue().get("email:code:" + email);
        } else {
            storedCode = redisTemplate.opsForValue().get("sms:code:" + email);
        }

        // 验证
        return code.equals(storedCode);
    }

    // 生成6位随机数字验证码
    private String generateCode() {
        Random random = new Random();
        return String.format("%06d", random.nextInt(999999));
    }

}
